import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios'
import type { IRequestConfig } from './type.ts'

class CustomRequest {
  axiosInstance: AxiosInstance

  constructor(config: IRequestConfig) {
    this.axiosInstance = axios.create(config)

    this.axiosInstance.interceptors.request.use(
      (config) => {
        console.log('全局请求成功拦截')
        return config
      },
      (error) => {
        console.log('全局请求失败拦截')
        return error
      }
    )

    this.axiosInstance.interceptors.response.use(
      (res) => {
        console.log('全局响应成功拦截')
        return res.data
      },
      (error) => {
        console.log('全局响应失败拦截')
        return error
      }
    )

    // 针对特定CustomRequest实例添加拦截器
    this.axiosInstance.interceptors.request.use(
      // @ts-ignore
      config?.interceptors?.requestInterceptors,
      config?.interceptors?.requestInterceptorsCatch
    )
  }

  // 封装网络请求的方法
  // T => IHomeData
  request<T = any>(config: IRequestConfig<T>) {
    /*// 不能在拦截器里单独处理单次请求--请求配置config会保留下来，后续也就有这个拦截了
    this.axiosInstance.interceptors.request.use(() => {
    }, () => {
    })*/

    // 单次请求成功拦截处理
    if (config?.interceptors?.requestInterceptors) {
      config = config.interceptors.requestInterceptors(config)
    }
    return new Promise<T>((resolve, reject) => {
      this.axiosInstance
        .request<any, T>(config)
        .then((res) => {
          // 单次响应成功拦截处理
          if (config?.interceptors?.responseInterceptors) {
            res = config.interceptors.responseInterceptors(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get<T = any>(config: IRequestConfig<T>) {
    return this.request({ ...config, method: 'GET' })
  }

  post<T = any>(config: IRequestConfig<T>) {
    return this.request({ ...config, method: 'POST' })
  }
}

export default CustomRequest
